package org.finesys.common.log.trace.reflect.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.finesys.common.log.annotation.FieldIgnore;
import org.finesys.common.log.annotation.ValidChild;
import org.finesys.common.log.trace.reflect.Reflect;
import org.finesys.common.log.trace.spi.annotation.Join;
import org.finesys.common.log.trace.util.LogstashUtil;
import org.finesys.common.sensitive.core.util.SensitiveFieldUtil;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Join
@Slf4j
public class JavaBeanParameterReflect implements Reflect {

    @Override
    public Object reflect(Object obj) throws UnsupportedEncodingException {
        if (Objects.isNull(obj)) {
            return null;
        }
        Field[] fields = FieldUtils.getAllFields(obj.getClass());
        Map<String, Object> result = new HashMap<>();

        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object argument = field.get(obj);
                String name = field.getName();
                if (field.getAnnotation(ValidChild.class) != null) {
                    argument = reflect(argument);
                }
                // 如果FieldOperate注解ignore值为true则不打印该字段内容
                if (field.getAnnotation(FieldIgnore.class) != null) {
                    continue;
                }
                //脱敏处理
                argument = SensitiveFieldUtil.getSensitiveArgument(field, argument);
                // 将处理后的请求参数放到map中
                result.put(name, argument);
            } catch (IllegalAccessException e) {
                log.error(LogstashUtil.exceptionMarker(), "IllegalAccessException", e);
            }
        }
        return result;
    }
}
